﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

using Ionic.Zip;

namespace Gamey
{
    public abstract class RomReader
    {
        public void PopulateRowFromZipFile(DataRow row, string zipFilePath)
        {
            byte[] bytes = ReadZipEntryWithExtension(zipFilePath, RomFileExtension);

            foreach (KeyValuePair<string, FieldReader> headerFieldLocation in GetFieldReaders())
            {
                string fieldName = headerFieldLocation.Key;
                FieldReader fieldReader = headerFieldLocation.Value;

                string value;
                if (fieldReader.TryReadField(bytes, out value))
                {
                    row.SetField(fieldName, value);
                }
            }
        }

        protected abstract string RomFileExtension { get; }

        protected abstract IDictionary<string, FieldReader> GetFieldReaders();

        protected byte[] ReadZipEntryWithExtension(string zipFilePath, string extension)
        {
            using (ZipFile zipFile = ZipFile.Read(zipFilePath))
            {
                ZipEntry smcFileEntry = zipFile.Entries.FirstOrDefault(e => Path.GetExtension(e.FileName) == extension);

                if (smcFileEntry != null)
                {
                    return ReadZipEntry(smcFileEntry);
                }
            }

            return null;
        }

        protected byte[] ReadZipEntry(ZipEntry zipEntry)
        {
            using (var stream = new MemoryStream())
            {
                zipEntry.Extract(stream);
                return stream.ToArray();
            }
        }
    }
}
